package com.lhl.mongo.controller;

import com.lhl.mongo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

/**
 * @author LHL
 * @date 2019/7/22
 */
@RestController
public class MongoController {


    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private GridFsTemplate gridFsTemplate;

    @PostMapping(value = "insert")
    public User insert() {
        User user = new User();
        user.setAge(30);
        user.setName("es");
        user.setPhone("12345678912");
        user.setSex("男");
        user.setCreateTime(new Date());

//        user.setId(110L);
        User insert = mongoTemplate.insert(user, "es");
//        mongoTemplate.save(insert, "es");
        return insert;
    }

//    @PostMapping(value = "insertbatch")
//    public User insertbatch() {
//
//        return insert;
//    }

    @GetMapping(value = "select/date/{date}")
    public List<User> getUserByDate(@PathVariable("date") String date) throws ParseException {
        Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);

        List<User> users = mongoTemplate.find(query(where("createTime").lte(date1)), User.class, "es");
        System.out.println(users);
        return users;
    }

    @GetMapping(value = "select")
    public List<User> select() {
        Query age = query(where("age").is(30));
        List<User> users = mongoTemplate.find(age, User.class, "es");
        return users;
    }

    @GetMapping(value = "get/{start}/{end}")
    public List<Map> get(@PathVariable("start") Long start, @PathVariable("end") Long end) {
        List<Map> objects = mongoTemplate.find(query(where("id").gte(start).andOperator(where("id").lte(end))), Map.class, "demo");
        return objects;
    }

    @GetMapping(value = "get1/{start}")
    public List<Map> get1(@PathVariable("start") Long start) {
        List<Map> objects = mongoTemplate.find(query(where("id").gte(start)), Map.class, "demo");
        return objects;
    }

    @DeleteMapping(value = "delete/{collection}")
    public String delete(@PathVariable("collection") String collection) {
        mongoTemplate.dropCollection(collection);
        return "ok";
    }

}
